/*
 * DCE400服务系统 -- 后端服务接口 -- 数据访问层 -- 客户数据访问
 * 包括：客户数据库增删改查
 *      客户登录记录插入、查找
 */
package dao

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"go.uber.org/zap"
	"strings"
	"time"
)

//********************************************
//Func  ：查询数据库：客户列表，分页查询。
//Method：GET
//Usage ：
//********************************************
func QueryCustomList(page, pageSize int, mobile string) (int64, []*entity.Customer, error) {
	offset := (page - 1) * pageSize
	session := db.Session().Table("customer")

	defer session.Close()
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	if pageSize > 0 {
		session.Limit(pageSize, offset)
	}
	customers := []*entity.Customer{}
	total, err := session.Omit("password").FindAndCount(&customers)
	if err != nil {
		return 0, nil, err
	}
	return total, customers, nil
}

//********************************************
//Func  ：查询数据库：指定客户的详情
//Method：GET
//Param：customerId 或 mobile
//Usage ：
//********************************************
func QueryCustomerDetail(mobile string, customerId int64) (*entity.Customer, error) {
	session := db.Session().Table("customer") //.Where("id=?",operatorId).Get(&operator)
	defer session.Close()

	if customerId > 0 {
		session = session.Where("id=?", customerId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}
	var customer entity.Customer
	has, err := session.Get(&customer)
	if err != nil || has == false {
		return nil, err
	}
	return &customer, nil
}

//********************************************
//Func  ：插入数据库：插入客户登录信息
//Method：GET
//Param：customerId 或 mobile
//Usage ：
//********************************************
func InsertCustmoerLoginLog(log entity.CustomerLoginLog) error {
	session := db.Session().Table("customer_login_log")
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	_, err = session.Insert(&log) //插入
	if err != nil {
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：添加新操作员（使用手机号作为唯一ID）
//Method：POST
//Usage ：
//********************************************
func InsertCustomer(customer entity.Customer) (*entity.Customer, error) {
	var err error
	if len(strings.TrimSpace(customer.Name)) <= 0 { //姓名（必填）/单位名称
		return nil, errors.New("name is none")
	}
	if len(strings.TrimSpace(customer.Mobile)) <= 0 { //手机（必填）
		return nil, errors.New("mobile is none")
	}
	customer.CreatedAt = time.Now()
	customer.Status = 0
	customer.Id = util.GenSnowflakeInt64()
	global.Log.Info("InsertCustomer: ", zap.Any("customer:", customer))

	session := db.Session().Table("customer")
	defer session.Close()

	err = session.Begin()
	if err != nil {
		return nil, errors.New("db session begin failed.")
	}

	_, err = session.Insert(&customer) //插入
	if err != nil {
		session.Rollback()
		return nil, err
	}
	err = session.Commit()
	if err != nil {
		return nil, err
	}

	var newer entity.Customer
	db.Session().Table("operator").
		Where("mobile =?", customer.Mobile).
		Desc("id").Get(&newer)
	return &newer, nil
}

//********************************************
//Func  ：更新Operator信息
//Method：POST
//Usage ：
//********************************************
func UpdateCustomer(customer entity.Customer) error {
	var err error
	if len(strings.TrimSpace(customer.Name)) <= 0 { //姓名（必填）/单位名称
		return errors.New("name is none")
	}
	if len(strings.TrimSpace(customer.Mobile)) <= 0 { //手机（必填）
		return errors.New("mobile is none")
	}

	session := db.Session().Table("customer")
	defer session.Close()

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Where("mobile=?", customer.Mobile).
		Cols("name,telephone,email,cert_type,id_number,ceo_name,cert_url").
		Update(customer) //更新

	if err != nil {
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

//********************************************
//Func  ：Customer删除
//Method：DELETE
//Usage ：客户-账号删除--物理删
//********************************************
func DeleteCustom(mobile string, customerId int64) error {
	if mobile == "" && customerId <= 0 {
		return errors.New("未指定操作员信息")
	}

	session := db.Session().Table("customer")
	defer session.Close()

	if customerId > 0 {
		session = session.Where("id=?", customerId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}
	var customer entity.Customer
	customer.Id = customerId
	customer.Mobile = mobile
	session.Begin()
	cnt, err := session.Delete(&customer)
	if err != nil {
		session.Rollback()
		return err
	}
	if cnt <= 0 {
		session.Rollback()
		return errors.New("移除用户数量0")
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：更新客户手机号
//Method：POST
//Usage ：操作员设置-绑定手机
//********************************************
func UpdateCustomerMobile(mobile string, customerId int64, newMobile string) error {
	var err error
	if len(strings.TrimSpace(mobile)) <= 0 && customerId <= 0 {
		return errors.New("mobile is none")
	}
	if len(strings.TrimSpace(newMobile)) <= 0 { //新手机（必填）
		return errors.New("new mobile is none")
	}
	if customerId <= 0 {
		return errors.New("mobile is none")
	}

	session := db.Session().Table("customer")
	defer session.Close()
	if customerId > 0 {
		session = session.Where("id=?", customerId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	var customer entity.Customer
	customer.Mobile = newMobile

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Cols("mobile").Update(customer)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：更新客户手机号
//Method：POST
//Usage ：操作员设置-绑定手机
//********************************************
func UpdateCustomerEmail(mobile string, customerId int64, email string) error {
	var err error
	if len(strings.TrimSpace(mobile)) <= 0 { //手机（必填）
		return errors.New("mobile is none")
	}
	if len(strings.TrimSpace(email)) <= 0 { //新手机（必填）
		return errors.New("new email is none")
	}
	if customerId <= 0 {
		return errors.New("mobile is none")
	}

	session := db.Session().Table("customer")
	defer session.Close()
	if customerId > 0 {
		session = session.Where("id=?", customerId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	var customer entity.Customer
	customer.Email = email

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Cols("email").Update(customer)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：客户修改密码
//Method：POST
//Usage ：
//********************************************
func UpdateCustomerPassword(mobile string, customerId int64, pwdSum string) error {
	var err error
	if len(strings.TrimSpace(mobile)) <= 0 && customerId <= 0 {
		return errors.New("mobile of id is none")
	}
	if len(strings.TrimSpace(pwdSum)) <= 0 { //PASSWORD
		return errors.New("new mobile is none")
	}
	if customerId <= 0 {
		return errors.New("custom id is none")
	}

	session := db.Session().Table("customer")
	defer session.Close()
	if customerId > 0 {
		session = session.Where("id=?", customerId)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	var customer entity.Customer
	customer.Password = pwdSum

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Cols("password").Update(customer)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}
